#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试 **kwargs 语法在字符串格式化中的处理
"""

import unittest
import sys
import os

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from tests.pytests.helpers.codegen_helpers import compile_chunk


class TestKwargsFormat(unittest.TestCase):

    def test_kwargs_format_basic(self):
        """测试基本的 **kwargs 格式化"""

        def format_with_kwargs(data: dict) -> str:
            return "Hello {name}, you are {age} years old".format(**data)

        block = compile_chunk(format_with_kwargs)
        # 验证生成的代码使用 mc::format_dict
        assert 'mc::format_dict("Hello {name}, you are {age} years old", data)' in block

    def test_kwargs_format_with_literal_dict(self):
        """测试使用字面值字典的 **kwargs 格式化"""

        def format_with_literal() -> str:
            return "User: {username}, ID: {user_id}".format(
                **{"username": "bob", "user_id": 123}
            )

        block = compile_chunk(format_with_literal)
        # 验证生成的代码使用展开的kwargs格式
        assert (
            'sformat("User: {username}, ID: {user_id}", ("username", "bob"), ("user_id", 123))'
            in block
        )

    def test_mixed_args_and_kwargs(self):
        """测试混合使用普通参数和 **kwargs"""

        def format_mixed(data: dict) -> str:
            return "Hello {name}, welcome to {place}".format(place="Python", **data)

        block = compile_chunk(format_mixed)
        # 在混合参数的情况下，应该优先使用 mc::format_dict
        # 因为 kwargs 参数的存在
        assert "mc::format_dict" in block

    def test_normal_format_without_kwargs(self):
        """测试没有 **kwargs 的普通格式化仍使用 sformat"""

        def format_normal() -> str:
            return "Hello {name}, you are {age} years old".format(name="David", age=25)

        block = compile_chunk(format_normal)
        # 验证普通格式化仍使用 sformat
        assert (
            'sformat("Hello {name}, you are {age} years old", ("name", "David"), ("age", 25))'
            in block
        )
        assert "mc::format_dict" not in block

    def test_kwargs_format_with_variable_dict(self):
        """测试使用变量字典的 **kwargs 格式化"""

        def format_with_variable() -> str:
            data = {"username": "charlie", "user_id": 456}
            return "User: {username}, ID: {user_id}".format(**data)

        block = compile_chunk(format_with_variable)
        # 验证生成的代码使用 mc::format_dict 处理变量字典
        assert 'mc::format_dict("User: {username}, ID: {user_id}", data)' in block
